#include <Arduino.h>
#include <unity.h>
#include "../src/SimpleCDNET.h"

// Mock serial for testing
class MockSerial : public HardwareSerial {
public:
    MockSerial() : HardwareSerial(0) {}
    void begin(unsigned long baud) override {}
    void end() override {}
    size_t write(uint8_t c) override { return 1; }
    int available() override { return 0; }
    int read() override { return -1; }
    int peek() override { return -1; }
    void flush() override {}
    operator bool() override { return true; }
};

SimpleCDNET cdnet;
MockSerial mockSerial;

void test_cdnet_initialization() {
    TEST_ASSERT_FALSE(cdnet.isInitialized());
    cdnet.begin(&mockSerial, 0x01);
    TEST_ASSERT_TRUE(cdnet.isInitialized());
    cdnet.end();
    TEST_ASSERT_FALSE(cdnet.isInitialized());
}

void test_send_l0() {
    cdnet.begin(&mockSerial, 0x01);
    uint8_t data[] = {0x01, 0x02, 0x03};
    
    cdnet.sendL0(0x02, 0x1000, data, 3);
    cdnet.sendL0(0x02, 0xFFFF, data, 0);
    
    cdnet.end();
}

void test_send_l1() {
    cdnet.begin(&mockSerial, 0x01);
    uint8_t data[] = {0x01, 0x02, 0x03};
    
    cdnet.sendL1(0x02, 0x1000, data, 3);
    cdnet.sendL1(0x02, 0xFFFF, data, 0);
    
    cdnet.end();
}

void test_port_numbers() {
    cdnet.begin(&mockSerial, 0x01);
    uint8_t data[] = {0x01};
    
    // Test standard ports
    cdnet.sendL0(0x02, 0x0000, data, 1);  // Broadcast
    cdnet.sendL0(0x02, 0x0001, data, 1);  // Discovery
    cdnet.sendL0(0x02, 0x0002, data, 1);  // Config
    cdnet.sendL0(0x02, 0x0003, data, 1);  // Data
    cdnet.sendL0(0x02, 0x0004, data, 1);  // Debug
    
    cdnet.end();
}

void test_max_data_length() {
    cdnet.begin(&mockSerial, 0x01);
    
    uint8_t maxData[248];  // L0 max
    cdnet.sendL0(0x02, 0x1000, maxData, 248);
    
    uint8_t maxL1Data[248];  // L1 max
    cdnet.sendL1(0x02, 0x1000, maxL1Data, 248);
    
    cdnet.end();
}

void setup() {
    UNITY_BEGIN();
    RUN_TEST(test_cdnet_initialization);
    RUN_TEST(test_send_l0);
    RUN_TEST(test_send_l1);
    RUN_TEST(test_port_numbers);
    RUN_TEST(test_max_data_length);
    UNITY_END();
}

void loop() {
    // Empty - tests run in setup
}